package com.panda.admin.login.auth.controller;

import com.panda.admin.login.auth.service.SystemUserService;
import com.panda.admin.result.Result;
import com.panda.admin.result.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.util.ObjectUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Map;


/**
 * author: tcy
 * createDate: 2022/10/27
 * description:登录控制
 */
@Api(tags = "登录控制")
@RestController
@RequestMapping("/oauth")
public class SystemUserController {

    @Autowired
    SystemUserService systemUserService;

    @Autowired
    TokenStore tokenStore;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    TokenEndpoint tokenEndpoint;

    @ApiOperation(value = "请求token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "grant_type", value = "授权模式", required = true),
            @ApiImplicitParam(name = "client_id", value = "客户端ID", required = true),
            @ApiImplicitParam(name = "client_secret", value = "客户端秘钥", required = true),
            @ApiImplicitParam(name = "username", value = "用户账号", required = true),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true)
    })
    @PostMapping("/token")
    public Result<Object> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        return Result.success(accessToken);
    }

    @ApiOperation(value = "校验token")
    @GetMapping("/check_token")
    public Result<String> checkToken(@RequestParam("token") String token) {

        OAuth2AccessToken oAuth2AccessToken = this.tokenStore.readAccessToken(token);
        if (ObjectUtils.isEmpty(oAuth2AccessToken) || oAuth2AccessToken.isExpired()){
            throw new ServiceException("token无法识别或已经过期");
        }

        OAuth2Authentication oAuth2Authentication = this.tokenStore.readAuthentication(token);
        if (ObjectUtils.isEmpty(oAuth2Authentication)){
            throw new ServiceException("验证信息无效或已过期");
        }
        int expiresIn = oAuth2AccessToken.getExpiresIn();
        return Result.success("token校验通过,有效时间:" + expiresIn + "s");
    }

}
